﻿
using Avalonia;
using Avalonia.Controls.Primitives;
using KinonekoSoftware.Foundation.UI.ViewModels;

namespace KinonekoSoftware.Platform.Controls
{
    public class ContentHost : TemplatedControl
    {
        public static readonly StyledProperty<ManagedLifetimeObject> ViewModelProperty;
        public static readonly DirectProperty<ContentHost, object>   ContentProperty;
        
        static ContentHost()
        {
            ViewModelProperty = AvaloniaProperty.Register<ContentHost, ManagedLifetimeObject>(nameof(ViewModel));
            ContentProperty   = AvaloniaProperty.RegisterDirect<ContentHost, object>(nameof(Content), x => x._content);

            ViewModelProperty.Changed.Subscribe(OnViewModelPropertyChanged);
        }

        private object _content;

        private static void OnViewModelPropertyChanged(AvaloniaPropertyChangedEventArgs<ManagedLifetimeObject> e)
        {
            var d        = (ContentHost)e.Sender;
            var newValue = e.GetNewValue<ManagedLifetimeObject>();
            
            if (newValue != null)
            {
                try
                {
                    var v = Xplat.Associate(newValue);
                    d.Content = v;
                }
                catch(Exception ex)
                {
                    //
                    var temp = new InternalErrorPageVM(ex, newValue.GetType());
                    var v    = Xplat.Associate(temp);

                    d.Content = v;
                }
            }
            else
            {
                d.Content = null;
            }
        }
        
        public ManagedLifetimeObject ViewModel
        {
            get => GetValue(ViewModelProperty);
            set => SetValue(ViewModelProperty, value);
        }
        
        public object Content
        {
            get => _content;
            private set => SetAndRaise(ContentProperty, ref _content, value);
        }
    }
}